import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwds.digital.bios.business.application.BiosBusinessApplication;
import com.jwds.digital.bios.business.core.constants.BeltCloudConstant;
import com.jwds.digital.bios.business.core.infrastructure.dto.feign.BasicDeviceReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.entity.basic.BasicDevice;
import com.jwds.digital.bios.business.core.infrastructure.entity.belt.*;
import com.jwds.digital.bios.business.core.infrastructure.telegram.BeltRouteBelongData;
import com.jwds.digital.bios.business.core.infrastructure.vo.feign.BasicDeviceRespVO;
import com.jwds.digital.bios.business.core.infrastructure.vo.feign.FlowCurrentJobRespVO;
import com.jwds.digital.bios.business.rpc.BiosBusinessRpcConfiguration;
import com.jwds.digital.bios.business.rpc.feign.BasicDeviceFeign;
import com.jwds.digital.bios.business.rpc.feign.FlowCurrentJobFeign;
import com.jwds.digital.bios.business.service.BiosBusinessServiceConfiguration;
import com.jwds.digital.bios.business.service.service.basic.IBasicDeviceService;
import com.jwds.digital.bios.business.service.service.belt.*;
import com.jwds.digital.bios.business.service.service.belt.impl.BeltPerformanceHourServiceImpl;
import com.jwds.tdc.framework.application.lib.BaseResponse;
import com.jwds.tdc.framework.cache.service.CacheService;
import com.jwds.tdc.framework.common.exception.BusinessException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * <p>BeltCloudGenerateTestData</p>
 *
 * @author 林柏云
 * @Date：2024/12/25 16:53
 */
@SpringBootTest(classes = BiosBusinessApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(value = "dev")
@ExtendWith(MockitoExtension.class)
public class BeltCloudGenerateTestData {

  @Resource
  private IBeltPerformanceMinuteService beltPerformanceMinuteService;

  @Resource
  private IBasicDeviceService basicDeviceService;

  @Resource
  private FlowCurrentJobFeign flowCurrentJobFeign;

  @Resource
  private IBeltPerformanceHourService beltPerformanceHourService;
  @Resource
  private IBeltPerformanceDayService beltPerformanceDayService;
  @Resource
  private IBeltPerformanceWeekService beltPerformanceWeekService;
  @Resource
  private IBeltPerformanceMonthService beltPerformanceMonthService;

  @Resource
  private IBeltHealthDayService beltHealthDayService;
  @Resource
  private IBeltHealthWeekService beltHealthWeekService;
  @Resource
  private IBeltHealthMonthService beltHealthMonthService;


  @Resource
  private CacheService cacheService;
    @Qualifier("com.jwds.digital.bios.business.rpc.feign.BasicDeviceFeign")
    @Autowired
    private BasicDeviceFeign basicDeviceFeign;

  @Test
  public void initRedisKey(){
    String dateTimeString = "2024-12-27 13:00:00";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime time = LocalDateTime.parse(dateTimeString, formatter);
    cacheService.setString(BeltCloudConstant.BC_BELT_HOUR_COLLECT_TIME_KEY, time.withMinute(0).withSecond(0).withNano(0).toString());
    cacheService.setString(BeltCloudConstant.BC_BELT_DAY_COLLECT_TIME_KEY, time.withHour(0).withMinute(0).withSecond(0).withNano(0).toString());
    cacheService.setString(BeltCloudConstant.BC_BELT_WEEK_COLLECT_TIME_KEY, time.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).withHour(0).withMinute(0).withSecond(0).withNano(0).toString());
    cacheService.setString(BeltCloudConstant.BC_BELT_MONTH_COLLECT_TIME_KEY, time.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0).toString());
  }

  @Test
  public void generateMinTestData() {
    // 假设一个作业30分钟，前5分钟空载，后5分钟空载，中间20分钟满载
    int loadStatus = 0; // 0:空载 1:满载

    List<FlowCurrentJobRespVO> flowCurrentJobRespList = flowCurrentJobFeign.currentExeList().getData();
    if(ObjectUtil.isNotNull(flowCurrentJobRespList) && flowCurrentJobRespList.size() > 0){
      for (FlowCurrentJobRespVO flowCurrentJobResp : flowCurrentJobRespList) {

        List<String> beltCodeList = Arrays.asList(flowCurrentJobResp.getFlowCode().split("_"));
        for (String beltCode : beltCodeList) {
          BasicDevice device = basicDeviceService.getOne(new LambdaQueryWrapper<BasicDevice>().eq(BasicDevice::getDeviceCode,beltCode).last("limit 1"));
          if(ObjectUtil.isNotNull(device) && ObjectUtil.isNotNull(device.getDeviceLength())){
            for(int i = 0; i<30; i++) {
              if(i < 5 || i > 25){
                loadStatus = 0;
              }else {
                loadStatus = 1;
              }
              BeltPerformanceMinute beltPerformanceMinute = new BeltPerformanceMinute();
              beltPerformanceMinute.setBeltCode(beltCode);
              beltPerformanceMinute.setFlowNo(flowCurrentJobResp.getFlowNo());
              beltPerformanceMinute.setTaskId(flowCurrentJobResp.getId());
              beltPerformanceMinute.setTaskType("S5");
              LocalDateTime startTime = getStartTime(flowCurrentJobResp);
              LocalDateTime endTime = getEndTime(flowCurrentJobResp);
              if(ObjectUtil.isNull(startTime)){
                String key = StrUtil.format("{}_{}_{}", BeltCloudConstant.BC_RUNNING_ROUTE_KEY, flowCurrentJobResp.getFlowNo(), flowCurrentJobResp.getId());
                cacheService.delete(key);
                break;
              }
              beltPerformanceMinute.setStartTime(startTime);
              beltPerformanceMinute.setEndTime(endTime);
              beltPerformanceMinute.setLoadStatus(loadStatus);
              beltPerformanceMinute.setAvgLoadRate(getAvgLoadRate(loadStatus));
              beltPerformanceMinute.setAvgPower(getAvgPower(loadStatus, device.getMotorRatedPower()));
              beltPerformanceMinute.setPowerConsumption(getPowerConsumption(loadStatus));
              beltPerformanceMinute.setRuntime(Integer.parseInt(ChronoUnit.SECONDS.between(beltPerformanceMinute.getStartTime(), beltPerformanceMinute.getEndTime()) + ""));
              beltPerformanceMinute.setPowerType(3);
              beltPerformanceMinute.setOperationEfficiency(getOperationEfficiency());
              beltPerformanceMinute.setAvgResistance(getAvgResistance(loadStatus));
              beltPerformanceMinute.setTotalTransport(getTotalTransport(loadStatus));
              beltPerformanceMinuteService.save(beltPerformanceMinute);
            }
          }
        }
      }
    }
    //设置上次作业统计时间]
    if(CollectionUtils.isNotEmpty(flowCurrentJobRespList)) {
      LocalDateTime time = flowCurrentJobRespList.get(0).getFlowStartTime();
      cacheService.setString(BeltCloudConstant.BC_BELT_HOUR_COLLECT_TIME_KEY, time.withMinute(0).withSecond(0).withNano(0).toString());
    }
  }

  @Test
  public void generateBeltPerformanceAndHealthTestDataBatch() {
    // 获取所有皮带
    BaseResponse<List<BasicDeviceRespVO>> list = basicDeviceFeign.list(new BasicDeviceReqDTO());
    List<BasicDeviceRespVO> data = list.getData();
    Random random = new Random();

    // 定义存放各实体的批量集合
    List<BeltPerformanceHour> hourList = new ArrayList<>();
    List<BeltPerformanceDay> dayList = new ArrayList<>();
    List<BeltPerformanceWeek> weekList = new ArrayList<>();
    List<BeltPerformanceMonth> monthList = new ArrayList<>();

    List<BeltHealthDay> healthDayList = new ArrayList<>();
    List<BeltHealthWeek> healthWeekList = new ArrayList<>();
    List<BeltHealthMonth> healthMonthList = new ArrayList<>();

    for (BasicDeviceRespVO basicDeviceRespVO : data) {

      // ============= 小时级数据 =============
      List<LocalDateTime> hourTimeList = BeltPerformanceHourServiceImpl
              .getTimeList(LocalDateTime.now().minusHours(10), LocalDateTime.now(), ChronoUnit.HOURS);
      for (LocalDateTime time : hourTimeList) {
        BeltPerformanceHour beltPerformanceHour = new BeltPerformanceHour();
        beltPerformanceHour.setBeltId(basicDeviceRespVO.getId());
        beltPerformanceHour.setBeltCode(basicDeviceRespVO.getDeviceCode());
        beltPerformanceHour.setStartTime(time);
        beltPerformanceHour.setEndTime(time.plusHours(1));
        beltPerformanceHour.setAvgLoadRate(getAvgLoadRate(1));
        beltPerformanceHour.setAvgNoLoadRate(getAvgLoadRate(0));
        beltPerformanceHour.setAvgAllLoadRate(getAvgLoadRate(1));
        beltPerformanceHour.setLoadRateRatio(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setWorkRate(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setWorkEfficiency(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setNoLoadPowerConsumption(getPowerConsumption(0));
        beltPerformanceHour.setLoadPowerConsumption(getPowerConsumption(1));
        beltPerformanceHour.setTotalPowerConsumption(getPowerConsumption(1));
        beltPerformanceHour.setAllRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setNoLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceHour.setOperationEfficiency(getOperationEfficiency());
        beltPerformanceHour.setSpikePowerConsumption(getPowerConsumption(1));
        beltPerformanceHour.setPeakPowerConsumption(getPowerConsumption(1));
        beltPerformanceHour.setValleyPowerConsumption(getPowerConsumption(1));
        beltPerformanceHour.setFlatPowerConsumption(getPowerConsumption(1));


        hourList.add(beltPerformanceHour);
      }

      // ============= 天级数据（性能 + 健康） =============
      List<LocalDateTime> dayTimeList = BeltPerformanceHourServiceImpl
              .getTimeList(LocalDateTime.now().minusDays(10), LocalDateTime.now(), ChronoUnit.DAYS);
      for (LocalDateTime time : dayTimeList) {
        // BeltPerformanceDay
        BeltPerformanceDay beltPerformanceDay = new BeltPerformanceDay();
        beltPerformanceDay.setBeltId(basicDeviceRespVO.getId());
        beltPerformanceDay.setBeltCode(basicDeviceRespVO.getDeviceCode());
        beltPerformanceDay.setStartTime(time);
        beltPerformanceDay.setEndTime(time.plusDays(1));
        beltPerformanceDay.setAvgLoadRate(getAvgLoadRate(1));
        beltPerformanceDay.setAvgNoLoadRate(getAvgLoadRate(0));
        beltPerformanceDay.setAvgAllLoadRate(getAvgLoadRate(1));
        beltPerformanceDay.setLoadRateRatio(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setWorkRate(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setWorkEfficiency(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setNoLoadPowerConsumption(getPowerConsumption(0));
        beltPerformanceDay.setLoadPowerConsumption(getPowerConsumption(1));
        beltPerformanceDay.setTotalPowerConsumption(getPowerConsumption(1));
        beltPerformanceDay.setAllRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setNoLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceDay.setOperationEfficiency(getOperationEfficiency());
        beltPerformanceDay.setSpikePowerConsumption(getPowerConsumption(1));
        beltPerformanceDay.setPeakPowerConsumption(getPowerConsumption(1));
        beltPerformanceDay.setValleyPowerConsumption(getPowerConsumption(1));
        beltPerformanceDay.setFlatPowerConsumption(getPowerConsumption(1));

        dayList.add(beltPerformanceDay);

        // BeltHealthDay
        BeltHealthDay beltHealthDay = new BeltHealthDay();
        beltHealthDay.setBeltName(basicDeviceRespVO.getDeviceName());
        beltHealthDay.setDate(time);
        beltHealthDay.setNoLoadResistance(getRandomBigDecimal(0,100, 2));
        beltHealthDay.setNoLoadResistancePower(getRandomBigDecimal(0,100, 2));
        beltHealthDay.setNoLoadResistanceIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthDay.setLoadFluctuation(random.nextInt(10));
        beltHealthDay.setLoadImpact(random.nextInt(10));
        beltHealthDay.setOverloadRateIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthDay.setHighStartupFrequency(random.nextInt(10));
        beltHealthDay.setTemperatureAnomaly(random.nextInt(10));
        beltHealthDay.setVibrationAnomaly(random.nextInt(10));
        beltHealthDay.setSlipAnomaly(random.nextInt(10));
        beltHealthDay.setRopeAnomaly(random.nextInt(10));
        beltHealthDay.setLightDeviationAnomaly(random.nextInt(10));
        beltHealthDay.setHeavyDeviationAnomaly(random.nextInt(10));
        beltHealthDay.setTearAnomaly(random.nextInt(10));
        beltHealthDay.setBlockageAnomaly(random.nextInt(10));
        beltHealthDay.setIsDeleted(0);
        healthDayList.add(beltHealthDay);
      }

      // ============= 周级数据（性能 + 健康） =============
      List<LocalDateTime> weekTimeList = BeltPerformanceHourServiceImpl
              .getTimeList(LocalDateTime.now().minusWeeks(10), LocalDateTime.now(), ChronoUnit.WEEKS);
      for (LocalDateTime time : weekTimeList) {
        // BeltPerformanceWeek
        BeltPerformanceWeek beltPerformanceWeek = new BeltPerformanceWeek();
        beltPerformanceWeek.setBeltId(basicDeviceRespVO.getId());
        beltPerformanceWeek.setBeltCode(basicDeviceRespVO.getDeviceCode());
        beltPerformanceWeek.setStartTime(time);
        beltPerformanceWeek.setEndTime(time.plusWeeks(1));
        beltPerformanceWeek.setAvgLoadRate(getAvgLoadRate(1));
        beltPerformanceWeek.setAvgNoLoadRate(getAvgLoadRate(0));
        beltPerformanceWeek.setAvgAllLoadRate(getAvgLoadRate(1));
        beltPerformanceWeek.setLoadRateRatio(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setWorkRate(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setWorkEfficiency(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setNoLoadPowerConsumption(getPowerConsumption(0));
        beltPerformanceWeek.setLoadPowerConsumption(getPowerConsumption(1));
        beltPerformanceWeek.setTotalPowerConsumption(getPowerConsumption(1));
        beltPerformanceWeek.setAllRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setNoLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceWeek.setOperationEfficiency(getOperationEfficiency());
        beltPerformanceWeek.setSpikePowerConsumption(getPowerConsumption(1));
        beltPerformanceWeek.setPeakPowerConsumption(getPowerConsumption(1));
        beltPerformanceWeek.setValleyPowerConsumption(getPowerConsumption(1));
        beltPerformanceWeek.setFlatPowerConsumption(getPowerConsumption(1));

        weekList.add(beltPerformanceWeek);

        // BeltHealthWeek
        BeltHealthWeek beltHealthWeek = new BeltHealthWeek();
        beltHealthWeek.setBeltName(basicDeviceRespVO.getDeviceName());
        beltHealthWeek.setDate(time);
        beltHealthWeek.setNoLoadResistance(getRandomBigDecimal(0,100, 2));
        beltHealthWeek.setNoLoadResistancePower(getRandomBigDecimal(0,100, 2));
        beltHealthWeek.setNoLoadResistanceIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthWeek.setLoadFluctuation(random.nextInt(10));
        beltHealthWeek.setLoadImpact(random.nextInt(10));
        beltHealthWeek.setOverloadRateIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthWeek.setHighStartupFrequency(random.nextInt(10));
        beltHealthWeek.setTemperatureAnomaly(random.nextInt(10));
        beltHealthWeek.setVibrationAnomaly(random.nextInt(10));
        beltHealthWeek.setSlipAnomaly(random.nextInt(10));
        beltHealthWeek.setRopeAnomaly(random.nextInt(10));
        beltHealthWeek.setLightDeviationAnomaly(random.nextInt(10));
        beltHealthWeek.setHeavyDeviationAnomaly(random.nextInt(10));
        beltHealthWeek.setTearAnomaly(random.nextInt(10));
        beltHealthWeek.setBlockageAnomaly(random.nextInt(10));
        beltHealthWeek.setIsDeleted(0);

        healthWeekList.add(beltHealthWeek);
      }

      // ============= 月级数据（性能 + 健康） =============
      List<LocalDateTime> monthTimeList = BeltPerformanceHourServiceImpl
              .getTimeList(LocalDateTime.now().minusMonths(10), LocalDateTime.now(), ChronoUnit.MONTHS);
      for (LocalDateTime time : monthTimeList) {
        // BeltPerformanceMonth
        BeltPerformanceMonth beltPerformanceMonth = new BeltPerformanceMonth();
        beltPerformanceMonth.setBeltId(basicDeviceRespVO.getId());
        beltPerformanceMonth.setBeltCode(basicDeviceRespVO.getDeviceCode());
        beltPerformanceMonth.setStartTime(time);
        beltPerformanceMonth.setEndTime(time.plusMonths(1));
        beltPerformanceMonth.setAvgLoadRate(getAvgLoadRate(1));
        beltPerformanceMonth.setAvgNoLoadRate(getAvgLoadRate(0));
        beltPerformanceMonth.setAvgAllLoadRate(getAvgLoadRate(1));
        beltPerformanceMonth.setLoadRateRatio(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setWorkRate(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setWorkEfficiency(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setNoLoadPowerConsumption(getPowerConsumption(0));
        beltPerformanceMonth.setLoadPowerConsumption(getPowerConsumption(1));
        beltPerformanceMonth.setTotalPowerConsumption(getPowerConsumption(1));
        beltPerformanceMonth.setAllRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setNoLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setLoadRuntime(getRandomBigDecimal(0,100, 2));
        beltPerformanceMonth.setOperationEfficiency(getOperationEfficiency());
        beltPerformanceMonth.setSpikePowerConsumption(getPowerConsumption(1));
        beltPerformanceMonth.setPeakPowerConsumption(getPowerConsumption(1));
        beltPerformanceMonth.setValleyPowerConsumption(getPowerConsumption(1));
        beltPerformanceMonth.setFlatPowerConsumption(getPowerConsumption(1));

        monthList.add(beltPerformanceMonth);

        // BeltHealthMonth
        BeltHealthMonth beltHealthMonth = new BeltHealthMonth();
        beltHealthMonth.setBeltName(basicDeviceRespVO.getDeviceName());
        beltHealthMonth.setDate(time);
        beltHealthMonth.setNoLoadResistance(getRandomBigDecimal(0,100, 2));
        beltHealthMonth.setNoLoadResistancePower(getRandomBigDecimal(0,100, 2));
        beltHealthMonth.setNoLoadResistanceIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthMonth.setLoadFluctuation(random.nextInt(10));
        beltHealthMonth.setLoadImpact(random.nextInt(10));
        beltHealthMonth.setOverloadRateIncrease(getRandomBigDecimal(0,100, 2));
        beltHealthMonth.setHighStartupFrequency(random.nextInt(10));
        beltHealthMonth.setTemperatureAnomaly(random.nextInt(10));
        beltHealthMonth.setVibrationAnomaly(random.nextInt(10));
        beltHealthMonth.setSlipAnomaly(random.nextInt(10));
        beltHealthMonth.setRopeAnomaly(random.nextInt(10));
        beltHealthMonth.setLightDeviationAnomaly(random.nextInt(10));
        beltHealthMonth.setHeavyDeviationAnomaly(random.nextInt(10));
        beltHealthMonth.setTearAnomaly(random.nextInt(10));
        beltHealthMonth.setBlockageAnomaly(random.nextInt(10));
        beltHealthMonth.setIsDeleted(0);

        healthMonthList.add(beltHealthMonth);
      }
    }

    // ==================== 统一批量插入 ====================
    beltPerformanceHourService.saveBatch(hourList);
    beltPerformanceDayService.saveBatch(dayList);
    beltPerformanceWeekService.saveBatch(weekList);
    beltPerformanceMonthService.saveBatch(monthList);

    beltHealthDayService.saveBatch(healthDayList);
    beltHealthWeekService.saveBatch(healthWeekList);
    beltHealthMonthService.saveBatch(healthMonthList);
  }

  public  BigDecimal getRandomBigDecimal(double min, double max, int scale) {
    Random random = new Random();

    // 生成在 [0, 1) 范围内的随机数
    double randomValue = min + (max - min) * random.nextDouble();

    // 转换为BigDecimal并设置小数位数
    BigDecimal result = BigDecimal.valueOf(randomValue)
            .setScale(scale, RoundingMode.HALF_UP);

    return result;
  }


  /**
   * 随机获取平均负载率（正常值）
   * @param loadStatus 0空载 1负载
   */
  private BigDecimal getAvgLoadRate(int loadStatus){

    double minUnLoadRate = 6.8;
    double maxUnLoadRate = 12.8;
    double minInLoadRate = 50.7;
    double maxInLoadRate = 90.5;
    if(loadStatus == 0){
        return new BigDecimal(minUnLoadRate + (maxUnLoadRate - minUnLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }else if(loadStatus == 1){
        return new BigDecimal(minInLoadRate + (maxInLoadRate - minInLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
    return BigDecimal.ZERO;
  }

  /**
   * 随机获取平均功率（正常值）
   * @param loadStatus
   * @param motorRatedPower 电机额定功率
   * @return
   */
  private BigDecimal getAvgPower(int loadStatus, BigDecimal motorRatedPower){

    double minUnPower = motorRatedPower.subtract(motorRatedPower.multiply(BigDecimal.valueOf(0.9))).doubleValue();
    double maxUnPower = motorRatedPower.subtract(motorRatedPower.multiply(BigDecimal.valueOf(0.7))).doubleValue();
    double minInPower = motorRatedPower.subtract(motorRatedPower.multiply(BigDecimal.valueOf(0.5))).doubleValue();
    double maxInPower = motorRatedPower.subtract(motorRatedPower.multiply(BigDecimal.valueOf(-0.1))).doubleValue();
    if(loadStatus == 0){
      return new BigDecimal(minUnPower + (maxUnPower - minUnPower) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }else if(loadStatus == 1){
      return new BigDecimal(minInPower + (maxInPower - minInPower) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
    return BigDecimal.ZERO;
  }

  /**
   * 获取耗电量（正常值）
   * @param loadStatus
   * @return
   */
  private BigDecimal getPowerConsumption(int loadStatus){

    double minUnLoadRate = 2.6;
    double maxUnLoadRate = 5.8;
    double minInLoadRate = 9.7;
    double maxInLoadRate = 17.5;
    if(loadStatus == 0){
      return new BigDecimal(minUnLoadRate + (maxUnLoadRate - minUnLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }else if(loadStatus == 1){
      return new BigDecimal(minInLoadRate + (maxInLoadRate - minInLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
    return BigDecimal.ZERO;
  }

  /**
   * 获取运行效率（正常值）
   * @return
   */
  private BigDecimal getOperationEfficiency(){
    double minUnLoadRate = 70;
    double maxUnLoadRate = 90;
    return new BigDecimal(minUnLoadRate + (maxUnLoadRate - minUnLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
  }

  /**
   * 获取阻力（正常值）
   * @return
   */
  private BigDecimal getAvgResistance(int loadStatus){
    double minUnLoadRate = 12.6;
    double maxUnLoadRate = 25.8;
    double minInLoadRate = 40.6;
    double maxInLoadRate = 75.4;
    if(loadStatus == 0){
      return new BigDecimal(minUnLoadRate + (maxUnLoadRate - minUnLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }else if(loadStatus == 1){
      return new BigDecimal(minInLoadRate + (maxInLoadRate - minInLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
    return BigDecimal.ZERO;
  }

  /**
   * 获取运输量（正常值）
   * @return
   */
  private BigDecimal getTotalTransport(int loadStatus){
    double minInLoadRate = 0.5;
    double maxInLoadRate = 1.5;
    if(loadStatus == 1){
      return new BigDecimal(minInLoadRate + (maxInLoadRate - minInLoadRate) * Math.random()).setScale(2,BigDecimal.ROUND_HALF_UP);
    }
    return BigDecimal.ZERO;
  }

  /**
   * 获取开始时间
   */
  private LocalDateTime getStartTime(FlowCurrentJobRespVO flowCurrentJobResp){
    String key = StrUtil.format("{}_{}_{}", BeltCloudConstant.BC_RUNNING_ROUTE_KEY, flowCurrentJobResp.getFlowNo(), flowCurrentJobResp.getId());
    if(!cacheService.isExists(key)){
      //不存在，并且没有结束时间，表示是正在运行的路线
      BeltRouteBelongData belongData = new BeltRouteBelongData();
      belongData.setFlowNo(flowCurrentJobResp.getFlowNo());
      belongData.setTaskId(flowCurrentJobResp.getId());
      belongData.setStartTime(flowCurrentJobResp.getFlowStartTime());
      belongData.setEndTime(flowCurrentJobResp.getFlowEndTime());
      belongData.setLastStatisticsStartTime(flowCurrentJobResp.getFlowStartTime());
      belongData.setLastStatisticsEndTime(flowCurrentJobResp.getFlowStartTime().plusMinutes(1).withSecond(0).withNano(0));
      cacheService.setStringExpired(key, JSONUtil.toJsonStr(belongData), BeltCloudConstant.BC_RUNNING_ROUTE_KEEP_TIME);
      return belongData.getLastStatisticsStartTime();
    }
    else{
      BeltRouteBelongData belongData = JSONUtil.toBean(cacheService.getString(key), BeltRouteBelongData.class);
      LocalDateTime lastStartTime = belongData.getLastStatisticsEndTime();
      if(lastStartTime.isEqual(flowCurrentJobResp.getFlowEndTime())){
        return null;
      }
      belongData.setLastStatisticsStartTime(lastStartTime);
      LocalDateTime lastEndTime = lastStartTime.plusMinutes(1).withSecond(0).withNano(0);
      if(flowCurrentJobResp.getFlowEndTime().isBefore(lastEndTime) || flowCurrentJobResp.getFlowEndTime().isEqual(lastEndTime)){
        lastEndTime = flowCurrentJobResp.getFlowEndTime();
      }
      belongData.setLastStatisticsEndTime(lastEndTime);
      cacheService.setStringExpired(key, JSONUtil.toJsonStr(belongData), BeltCloudConstant.BC_RUNNING_ROUTE_KEEP_TIME);
      return belongData.getLastStatisticsStartTime();
    }
  }

  /**
   * 获取结束时间
   */
  private LocalDateTime getEndTime(FlowCurrentJobRespVO flowCurrentJobResp){
    String key = StrUtil.format("{}_{}_{}", BeltCloudConstant.BC_RUNNING_ROUTE_KEY, flowCurrentJobResp.getFlowNo(), flowCurrentJobResp.getId());
    BeltRouteBelongData belongData = JSONUtil.toBean(cacheService.getString(key), BeltRouteBelongData.class);
    return belongData.getLastStatisticsEndTime();
  }
}
